<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">
  <meta http-equiv="Cache-Control" content="no-transform">
  <meta http-equiv="Cache-Control" content="no-siteapp">
  <meta name="baidu-site-verification" content="code-Qk3hgFvTdc">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gitee.com","root":"/","scheme":"Gemini","version":"7.8.0","exturl":true,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":true},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":true,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"disqus","storage":true,"lazyload":false,"nav":{"disqus":{"text":"Load Disqus","order":-1}}},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="Nginx如何支持HTTPS 随着我们网站用户的增多，我们会逐渐意识到HTTPS加密的重要性。在不修改现有代码的情况下，要从HTTP升级到HTTPS，让Nginx支持HTTPS是个很好的选择。今天我们来讲下如何从Nginx入手，从HTTP升级到HTTPS，同时支持静态网站和SpringBoot应用，希望对大家有所帮助！">
<meta property="og:type" content="article">
<meta property="og:title" content="Nginx如何支持HTTPS？">
<meta property="og:url" content="https://gitee.com/feege/feege.git/2021/08/11/Nginx%E5%A6%82%E4%BD%95%E6%94%AF%E6%8C%81HTTPS/index.html">
<meta property="og:site_name" content="云记">
<meta property="og:description" content="Nginx如何支持HTTPS 随着我们网站用户的增多，我们会逐渐意识到HTTPS加密的重要性。在不修改现有代码的情况下，要从HTTP升级到HTTPS，让Nginx支持HTTPS是个很好的选择。今天我们来讲下如何从Nginx入手，从HTTP升级到HTTPS，同时支持静态网站和SpringBoot应用，希望对大家有所帮助！">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/images/Nginx%E5%A6%82%E4%BD%95%E6%94%AF%E6%8C%81HTTPS/nginx_https_start_01.png">
<meta property="og:image" content="https://gitee.com/images/Nginx%E5%A6%82%E4%BD%95%E6%94%AF%E6%8C%81HTTPS/nginx_https_start_02.png">
<meta property="og:image" content="https://gitee.com/images/Nginx%E5%A6%82%E4%BD%95%E6%94%AF%E6%8C%81HTTPS/nginx_https_start_03.png">
<meta property="og:image" content="https://gitee.com/images/Nginx%E5%A6%82%E4%BD%95%E6%94%AF%E6%8C%81HTTPS/nginx_https_start_04.png">
<meta property="og:image" content="https://gitee.com/images/Nginx%E5%A6%82%E4%BD%95%E6%94%AF%E6%8C%81HTTPS/nginx_https_start_05.png">
<meta property="og:image" content="https://gitee.com/images/Nginx%E5%A6%82%E4%BD%95%E6%94%AF%E6%8C%81HTTPS/nginx_https_start_06.png">
<meta property="og:image" content="https://gitee.com/images/Nginx%E5%A6%82%E4%BD%95%E6%94%AF%E6%8C%81HTTPS/nginx_https_start_07.png">
<meta property="og:image" content="https://gitee.com/images/Nginx%E5%A6%82%E4%BD%95%E6%94%AF%E6%8C%81HTTPS/nginx_https_start_08.png">
<meta property="og:image" content="https://gitee.com/images/Nginx%E5%A6%82%E4%BD%95%E6%94%AF%E6%8C%81HTTPS/nginx_https_start_09.png">
<meta property="article:published_time" content="2021-08-11T08:01:25.279Z">
<meta property="article:modified_time" content="2021-08-11T08:06:44.102Z">
<meta property="article:author" content="云记">
<meta property="article:tag" content="Java,面试,offer,技术,微服务,分布式,中间件,数据库,bat">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/images/Nginx%E5%A6%82%E4%BD%95%E6%94%AF%E6%8C%81HTTPS/nginx_https_start_01.png">

<link rel="canonical" href="https://gitee.com/feege/feege.git/2021/08/11/Nginx%E5%A6%82%E4%BD%95%E6%94%AF%E6%8C%81HTTPS/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Nginx如何支持HTTPS？ | 云记</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">云记</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">云记</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">5</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">12</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>
  <a role="button" class="book-mark-link book-mark-link-fixed"></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/feege/feege.git/2021/08/11/Nginx%E5%A6%82%E4%BD%95%E6%94%AF%E6%8C%81HTTPS/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="云记">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="云记">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Nginx如何支持HTTPS？
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-08-11 16:01:25" itemprop="dateCreated datePublished" datetime="2021-08-11T16:01:25+08:00">2021-08-11</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E5%88%86%E5%B8%83%E5%BC%8F-%E5%BE%AE%E6%9C%8D%E5%8A%A1/" itemprop="url" rel="index"><span itemprop="name">分布式/微服务</span></a>
                </span>
            </span>

          
            <span id="/2021/08/11/Nginx%E5%A6%82%E4%BD%95%E6%94%AF%E6%8C%81HTTPS/" class="post-meta-item leancloud_visitors" data-flag-title="Nginx如何支持HTTPS？" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2021/08/11/Nginx%E5%A6%82%E4%BD%95%E6%94%AF%E6%8C%81HTTPS/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2021/08/11/Nginx%E5%A6%82%E4%BD%95%E6%94%AF%E6%8C%81HTTPS/" itemprop="commentCount"></span>
    </a>
  </span>
  
  <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>5.6k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>5 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="Nginx如何支持HTTPS"><a href="#Nginx如何支持HTTPS" class="headerlink" title="Nginx如何支持HTTPS"></a>Nginx如何支持HTTPS</h1><blockquote>
<p>随着我们网站用户的增多，我们会逐渐意识到HTTPS加密的重要性。在不修改现有代码的情况下，要从HTTP升级到HTTPS，让Nginx支持HTTPS是个很好的选择。今天我们来讲下如何从Nginx入手，从HTTP升级到HTTPS，同时支持静态网站和SpringBoot应用，希望对大家有所帮助！</p>
<span id="more"></span>
</blockquote>
<h2 id="生成SSL自签名证书"><a href="#生成SSL自签名证书" class="headerlink" title="生成SSL自签名证书"></a>生成SSL自签名证书</h2><blockquote>
<p>虽然自签名证书浏览器认为并不是安全的，但是学习下SSL证书的生成还是很有必要的！</p>
</blockquote>
<ul>
<li>首先创建SSL证书私钥，期间需要输入两次用户名和密码，生成文件为<code>blog.key</code>；</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">openssl genrsa -des3 -out blog.key 2048Copy to clipboardErrorCopied</span><br></pre></td></tr></table></figure>

<ul>
<li>利用私钥生成一个不需要输入密码的密钥文件，生成文件为<code>blog_nopass.key</code>；</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">openssl rsa -<span class="keyword">in</span> blog.key -out blog_nopass.keyCopy to clipboardErrorCopied</span><br></pre></td></tr></table></figure>

<ul>
<li>创建SSL证书签名请求文件，生成SSL证书时需要使用到，生成文件为<code>blog.csr</code>；</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">openssl req -new -key blog.key -out blog.csrCopy to clipboardErrorCopied</span><br></pre></td></tr></table></figure>

<ul>
<li>在生成过程中，我们需要输入一些信息，需要注意的是<code>Common Name</code>需要和网站域名一致；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">Enter pass phrase for blog.key:</span><br><span class="line">-----</span><br><span class="line">Country Name (2 letter code) [XX]:CN                                         # 国家代码</span><br><span class="line">State or Province Name (full name) []:jiangsu                                # 省份</span><br><span class="line">Locality Name (eg, city) [Default City]:jiangsu                              # 城市</span><br><span class="line">Organization Name (eg, company) [Default Company Ltd]:macrozheng             # 机构名称</span><br><span class="line">Organizational Unit Name (eg, section) []:dev                                # 单位名称</span><br><span class="line">Common Name (eg, your name or your server&#x27;s hostname) []:blog.macrozheng.com # 网站域名</span><br><span class="line">Email Address []:macrozheng@qq.com                                           # 邮箱</span><br><span class="line"></span><br><span class="line">Please enter the following &#x27;extra&#x27; attributes</span><br><span class="line">to be sent with your certificate request</span><br><span class="line">A challenge password []:                                                     # 私钥保护密码,可以不输入直接回车</span><br><span class="line">An optional company name []:                                                 # 可选公司名称，可以不输入直接回车Copy to clipboardErrorCopied</span><br></pre></td></tr></table></figure>

<ul>
<li>生成SSL证书，有效期为365天，生成文件为<code>blog.crt</code>；</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">openssl x509 -req -days 365 -<span class="keyword">in</span> blog.csr -signkey blog.key -out blog.crtCopy to clipboardErrorCopied</span><br></pre></td></tr></table></figure>

<ul>
<li>其实最终有用的文件是两个，一个是证书文件<code>blog.crt</code>，另一个是不需要输入密码的证书私钥文件<code>blog_nopass.key</code>。</li>
</ul>
<h2 id="Nginx支持HTTPS"><a href="#Nginx支持HTTPS" class="headerlink" title="Nginx支持HTTPS"></a>Nginx支持HTTPS</h2><blockquote>
<p>SSL证书生成好了，接下来我们就可以配置Nginx来支持HTTPS了！</p>
</blockquote>
<h3 id="安装Nginx"><a href="#安装Nginx" class="headerlink" title="安装Nginx"></a>安装Nginx</h3><ul>
<li>我们还是使用在Docker容器中安装Nginx的方式，先下载Nginx的Docker镜像；</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker pull nginx:1.10Copy to clipboardErrorCopied</span><br></pre></td></tr></table></figure>

<ul>
<li>下载完成后先运行一次Nginx，由于之后我们要把宿主机的Nginx配置文件映射到Docker容器中去，运行一次方便我们拷贝默认配置；</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">docker run -p 80:80 --name nginx \</span><br><span class="line">-v /mydata/nginx/html:/usr/share/nginx/html \</span><br><span class="line">-v /mydata/nginx/logs:/var/<span class="built_in">log</span>/nginx  \</span><br><span class="line">-d nginx:1.10Copy to clipboardErrorCopied</span><br></pre></td></tr></table></figure>

<ul>
<li>运行成功后将容器中的Nginx配置目录拷贝到宿主机上去；</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker container cp nginx:/etc/nginx /mydata/nginx/Copy to clipboardErrorCopied</span><br></pre></td></tr></table></figure>

<ul>
<li>将宿主机上的<code>nginx</code>目录改名为<code>conf</code>，要不然<code>/mydata/nginx/nginx</code>这个配置文件目录看着有点别扭；</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mv /mydata/nginx/nginx /mydata/nginx/confCopy to clipboardErrorCopied</span><br></pre></td></tr></table></figure>

<ul>
<li>创建的Nginx容器复制完配置后就没用了，停止并删除容器；</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">docker stop nginx</span><br><span class="line">docker rm nginxCopy to clipboardErrorCopied</span><br></pre></td></tr></table></figure>

<ul>
<li>使用Docker命令重新启动Nginx服务，需要映射好配置文件，由于我们要支持HTTPS，还需要开放<code>443</code>端口。</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">docker run -p 80:80 -p 443:443 --name nginx \</span><br><span class="line">-v /mydata/nginx/html:/usr/share/nginx/html \</span><br><span class="line">-v /mydata/nginx/logs:/var/<span class="built_in">log</span>/nginx  \</span><br><span class="line">-v /mydata/nginx/conf:/etc/nginx \</span><br><span class="line">-d nginx:1.10Copy to clipboardErrorCopied</span><br></pre></td></tr></table></figure>

<h3 id="配置支持HTTPS"><a href="#配置支持HTTPS" class="headerlink" title="配置支持HTTPS"></a>配置支持HTTPS</h3><ul>
<li>将我们生成好的SSL证书和私钥拷贝到Nginx的<code>html/ssl</code>目录下；</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">cp blog_nopass.key /mydata/nginx/html/ssl/</span><br><span class="line">cp blog.crt /mydata/nginx/html/ssl/Copy to clipboardErrorCopied</span><br></pre></td></tr></table></figure>

<ul>
<li>接下来我们需要给<code>blog.macrozheng.com</code>这个域名添加HTTPS支持，在<code>/mydata/nginx/conf/conf.d/</code>目录下添加Nginx配置文件<code>blog.conf</code>，配置文件内容如下；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line">server &#123;</span><br><span class="line">    listen       80; # 同时支持HTTP</span><br><span class="line">    listen       443 ssl; # 添加HTTPS支持</span><br><span class="line">    server_name  blog.macrozheng.com;</span><br><span class="line"></span><br><span class="line">    #SSL配置</span><br><span class="line">    ssl_certificate      /usr/share/nginx/html/ssl/blog/blog.crt; # 配置证书</span><br><span class="line">    ssl_certificate_key  /usr/share/nginx/html/ssl/blog/blog_nopass.key; # 配置证书私钥</span><br><span class="line">    ssl_protocols        TLSv1 TLSv1.1 TLSv1.2; # 配置SSL协议版本</span><br><span class="line">    ssl_ciphers          ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE; # 配置SSL加密算法</span><br><span class="line">    ssl_prefer_server_ciphers  on; # 优先采取服务器算法</span><br><span class="line">    ssl_session_cache    shared:SSL:10m; # 配置共享会话缓存大小</span><br><span class="line">    ssl_session_timeout  10m; # 配置会话超时时间</span><br><span class="line"></span><br><span class="line">    location / &#123;</span><br><span class="line">        root   /usr/share/nginx/html/www;</span><br><span class="line">        index  index.html index.htm;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    location /admin &#123;</span><br><span class="line">        alias   /usr/share/nginx/html/admin;</span><br><span class="line">        index  index.html index.htm;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    location /app &#123;</span><br><span class="line">        alias   /usr/share/nginx/html/app;</span><br><span class="line">        index  index.html index.htm;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    error_page   500 502 503 504  /50x.html;</span><br><span class="line">    location = /50x.html &#123;</span><br><span class="line">        root   /usr/share/nginx/html;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;Copy to clipboardErrorCopied</span><br></pre></td></tr></table></figure>

<ul>
<li>通过<code>HTTPS</code>访问<code>blog.macrozheng.com</code>这个域名，由于我们使用的是自己签名的SSL证书，浏览器会提示<code>您的连接不是私密连接</code>，点击继续前往可以通过HTTPS正常访问；</li>
</ul>
<p><img src="/images/Nginx%E5%A6%82%E4%BD%95%E6%94%AF%E6%8C%81HTTPS/nginx_https_start_01.png" alt="img"></p>
<ul>
<li>我们可以查看下证书的<code>颁发者</code>信息，可以发现正好是之前我们创建SSL证书签名请求文件时录入的信息；</li>
</ul>
<p><img src="/images/Nginx%E5%A6%82%E4%BD%95%E6%94%AF%E6%8C%81HTTPS/nginx_https_start_02.png" alt="img"></p>
<ul>
<li>接下来我们需要给<code>api.macrozheng.com</code>这个域名添加HTTPS支持，通过这个域名可以使用HTTPS访问我们的SpringBoot应用，<code>api.crt</code>和<code>api_nopass.key</code>文件需要自行生成，在<code>/mydata/nginx/conf/conf.d/</code>目录下添加Nginx配置文件<code>api.conf</code>，配置文件内容如下；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">server &#123;</span><br><span class="line">    listen       80; # 同时支持HTTP</span><br><span class="line">    listen       443 ssl; # 添加HTTPS支持</span><br><span class="line">    server_name  api.macrozheng.com; #修改域名</span><br><span class="line"></span><br><span class="line">    #ssl配置</span><br><span class="line">    ssl_certificate      /usr/share/nginx/html/ssl/api/api.crt; # 配置证书</span><br><span class="line">    ssl_certificate_key  /usr/share/nginx/html/ssl/api/api_nopass.key; # 配置证书私钥</span><br><span class="line">    ssl_protocols        TLSv1 TLSv1.1 TLSv1.2; # 配置SSL协议版本 # 配置SSL加密算法</span><br><span class="line">    ssl_ciphers          ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;</span><br><span class="line">    ssl_prefer_server_ciphers  on; # 优先采取服务器算法</span><br><span class="line">    ssl_session_cache    shared:SSL:10m; # 配置共享会话缓存大小</span><br><span class="line">    ssl_session_timeout  10m; # 配置会话超时时间</span><br><span class="line"></span><br><span class="line">    location / &#123;</span><br><span class="line">        proxy_pass   http://192.168.3.101:8080; # 设置代理服务访问地址</span><br><span class="line">        proxy_set_header  Host $http_host; # 设置客户端真实的域名（包括端口号）</span><br><span class="line">        proxy_set_header  X-Real-IP  $remote_addr; # 设置客户端真实IP</span><br><span class="line">        proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for; # 设置在多层代理时会包含真实客户端及中间每个代理服务器的IP</span><br><span class="line">        proxy_set_header X-Forwarded-Proto $scheme; # 设置客户端真实的协议（http还是https）</span><br><span class="line">        index  index.html index.htm;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    error_page   500 502 503 504  /50x.html;</span><br><span class="line">    location = /50x.html &#123;</span><br><span class="line">        root   /usr/share/nginx/html;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;Copy to clipboardErrorCopied</span><br></pre></td></tr></table></figure>

<ul>
<li>通过<code>HTTPS</code>访问<code>api.macrozheng.com</code>这个域名，访问地址为：<span class="exturl" data-url="aHR0cHM6Ly9hcGkubWFjcm96aGVuZy5jb20vc3dhZ2dlci11aS5odG1s">https://api.macrozheng.com/swagger-ui.html<i class="fa fa-external-link-alt"></i></span></li>
</ul>
<p><img src="/images/Nginx%E5%A6%82%E4%BD%95%E6%94%AF%E6%8C%81HTTPS/nginx_https_start_03.png" alt="img"></p>
<ul>
<li>任意调用一个接口测试下，比如说登录接口，可以发现已经可以通过HTTPS正常访问SpringBoot应用提供的接口。</li>
</ul>
<p><img src="/images/Nginx%E5%A6%82%E4%BD%95%E6%94%AF%E6%8C%81HTTPS/nginx_https_start_04.png" alt="img"></p>
<h2 id="使用受信任的证书"><a href="#使用受信任的证书" class="headerlink" title="使用受信任的证书"></a>使用受信任的证书</h2><blockquote>
<p>之前我们使用的是自签名的SSL证书，对于浏览器来说是无效的。使用权威机构颁发的SSL证书浏览器才会认为是有效的，这里给大家推荐两种申请免费SSL证书的方法，一种是从阿里云申请，另一种是从FreeSSL申请。</p>
</blockquote>
<h3 id="阿里云证书"><a href="#阿里云证书" class="headerlink" title="阿里云证书"></a>阿里云证书</h3><ul>
<li>阿里云上可以申请的免费证书目前只有支持单个域名的DV级SSL证书。比如说你有<code>blog.macrozheng.com</code>和<code>api.macrozheng.com</code>两个二级域名需要使用HTTPS，就需要申请两个SSL证书。</li>
</ul>
<p><img src="/images/Nginx%E5%A6%82%E4%BD%95%E6%94%AF%E6%8C%81HTTPS/nginx_https_start_05.png" alt="img"></p>
<ul>
<li>申请成功后点击下载Nginx证书即可；</li>
</ul>
<p><img src="/images/Nginx%E5%A6%82%E4%BD%95%E6%94%AF%E6%8C%81HTTPS/nginx_https_start_06.png" alt="img"></p>
<ul>
<li>下载完成后解压会有下面两个文件；</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">blog.macrozheng.com.key <span class="comment"># 证书私钥文件</span></span><br><span class="line">blog.macrozheng.com.pem <span class="comment"># 证书文件Copy to clipboardErrorCopied</span></span><br></pre></td></tr></table></figure>

<ul>
<li>拷贝证书文件到Nginx的指定目录下，然后修改配置文件<code>blog.conf</code>，只要修改证书配置路径即可，修改完成后重启Nginx；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">#SSL配置</span><br><span class="line">ssl_certificate      /usr/share/nginx/html/ssl/blog/blog.macrozheng.com.pem; # 配置证书</span><br><span class="line">ssl_certificate_key  /usr/share/nginx/html/ssl/blog/blog.macrozheng.com.key; # 配置证书私钥Copy to clipboardErrorCopied</span><br></pre></td></tr></table></figure>

<ul>
<li>再次通过HTTPS访问<code>blog.macrozheng.com</code>这个域名，发现证书已经有效了，连接也是安全的了。</li>
</ul>
<p><img src="/images/Nginx%E5%A6%82%E4%BD%95%E6%94%AF%E6%8C%81HTTPS/nginx_https_start_07.png" alt="img"></p>
<h3 id="FreeSSL证书"><a href="#FreeSSL证书" class="headerlink" title="FreeSSL证书"></a>FreeSSL证书</h3><ul>
<li>如果你有使用通配符域名的需求，可以上<code>FreeSSL</code>申请SSL证书，不过免费的有效期只有3个月，这就意味着你过3个月就要重新申请一次了。</li>
</ul>
<p><img src="/images/Nginx%E5%A6%82%E4%BD%95%E6%94%AF%E6%8C%81HTTPS/nginx_https_start_08.png" alt="img"></p>
<ul>
<li>附上官网地址：<span class="exturl" data-url="aHR0cHM6Ly9mcmVlc3NsLmNuLw==">https://freessl.cn/<i class="fa fa-external-link-alt"></i></span></li>
</ul>
<h3 id="使用acme-sh自动申请证书"><a href="#使用acme-sh自动申请证书" class="headerlink" title="使用acme.sh自动申请证书"></a>使用<code>acme.sh</code>自动申请证书</h3><ul>
<li><code>acme.sh</code>脚本实现了<code>acme</code>协议, 可以从<code>letsencrypt</code>生成免费的证书。一般我们申请的证书有效期都是1年，过期就要重新申请了，使用<code>acme.sh</code>脚本可以实现到期自动申请，再也不用担心证书过期了！</li>
</ul>
<p><img src="/images/Nginx%E5%A6%82%E4%BD%95%E6%94%AF%E6%8C%81HTTPS/nginx_https_start_09.png" alt="img"></p>

    </div>

    
    
    
        <div class="reward-container">
  <div></div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/images/wechatpay.png" alt="云记 微信支付">
        <p>微信支付</p>
      </div>
      
      <div style="display: inline-block;">
        <img src="/images/alipay.png" alt="云记 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>


      <footer class="post-footer">

        
  <div class="post-widgets">
    <div class="wp_rating">
      <div id="wpac-rating"></div>
    </div>
  </div>


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/08/10/RabbitMQ%E5%AE%9E%E7%8E%B0%E5%BB%B6%E8%BF%9F%E6%B6%88%E6%81%AF/" rel="prev" title="RabbitMQ实现延迟消息">
      <i class="fa fa-chevron-left"></i> RabbitMQ实现延迟消息
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/08/12/%E5%9F%BA%E4%BA%8E%E9%98%BF%E9%87%8C%E5%B7%B4%E5%B7%B4seata%E7%9A%84%E5%88%86%E5%B8%83%E5%BC%8F%E4%BA%8B%E5%8A%A1/" rel="next" title="基于阿里巴巴seata的分布式事务实践">
      基于阿里巴巴seata的分布式事务实践 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Nginx%E5%A6%82%E4%BD%95%E6%94%AF%E6%8C%81HTTPS"><span class="nav-number">1.</span> <span class="nav-text">Nginx如何支持HTTPS</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%94%9F%E6%88%90SSL%E8%87%AA%E7%AD%BE%E5%90%8D%E8%AF%81%E4%B9%A6"><span class="nav-number">1.1.</span> <span class="nav-text">生成SSL自签名证书</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Nginx%E6%94%AF%E6%8C%81HTTPS"><span class="nav-number">1.2.</span> <span class="nav-text">Nginx支持HTTPS</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AE%89%E8%A3%85Nginx"><span class="nav-number">1.2.1.</span> <span class="nav-text">安装Nginx</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E9%85%8D%E7%BD%AE%E6%94%AF%E6%8C%81HTTPS"><span class="nav-number">1.2.2.</span> <span class="nav-text">配置支持HTTPS</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8%E5%8F%97%E4%BF%A1%E4%BB%BB%E7%9A%84%E8%AF%81%E4%B9%A6"><span class="nav-number">1.3.</span> <span class="nav-text">使用受信任的证书</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E9%98%BF%E9%87%8C%E4%BA%91%E8%AF%81%E4%B9%A6"><span class="nav-number">1.3.1.</span> <span class="nav-text">阿里云证书</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#FreeSSL%E8%AF%81%E4%B9%A6"><span class="nav-number">1.3.2.</span> <span class="nav-text">FreeSSL证书</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8acme-sh%E8%87%AA%E5%8A%A8%E7%94%B3%E8%AF%B7%E8%AF%81%E4%B9%A6"><span class="nav-number">1.3.3.</span> <span class="nav-text">使用acme.sh自动申请证书</span></a></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">云记</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">12</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">5</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://gitee.com/feege" title="GitHub → https:&#x2F;&#x2F;gitee.com&#x2F;feege"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">云记</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
    <span title="站点总字数">217k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">3:18</span>
</div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>

<script src="/js/bookmark.js"></script>




  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>



  <script>
  if (CONFIG.page.isPost) {
    wpac_init = window.wpac_init || [];
    wpac_init.push({
      widget: 'Rating',
      id    : ,
      el    : 'wpac-rating',
      color : 'fc6423'
    });
    (function() {
      if ('WIDGETPACK_LOADED' in window) return;
      WIDGETPACK_LOADED = true;
      var mc = document.createElement('script');
      mc.type = 'text/javascript';
      mc.async = true;
      mc.src = '//embed.widgetpack.com/widget.js';
      var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(mc, s.nextSibling);
    })();
  }
  </script>

  
<script src="/js/local-search.js"></script>











<script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js', () => {
    mermaid.initialize({
      theme    : 'forest',
      logLevel : 3,
      flowchart: { curve     : 'linear' },
      gantt    : { axisFormat: '%m/%d/%Y' },
      sequence : { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script>


  

  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : 'QCF1KJ4ILmj73nVybNhgiHEJ-gzGzoHsz',
      appKey     : 'di34H8f5jhsb77nm4gtqtxQu',
      placeholder: "发表下你的看法!",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : true,
      lang       : 'zh-cn' || 'zh-cn',
      path       : location.pathname,
      recordIP   : true,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>
